import { provincesWithCities } from '@/assets/location';
import { shopsAddUsingPost } from '@/services/yu/shangpinxiangguanjiekou';
import { AlignLeftOutlined, CloseCircleOutlined, PlusOutlined, SmileOutlined } from '@ant-design/icons';
import {
  ProForm,
  ProFormDateRangePicker,
  ProFormDigit,
  ProFormGroup,
  ProFormList,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, Cascader, Col, Form, Modal, Row, Upload, message } from 'antd';
import React, { useState } from 'react';
// import { PlusOutlined, UndoOutlined } from '@ant-design/icons';

//类型
interface CreateProductFormProps {
  modalVisible: boolean;
  onCancel: () => void;
  

 
}
//级联类型
interface Option {
  value: string | number;
  label: string;
  children?: Option[];
}
//级联数据封装
const options: Option[] = provincesWithCities.map((item) => ({
  value: item.province,
  label: item.province,
  children: item.cities.map((city) => ({
    value: city,
    label: city,
  })),
}));

//图片格式
function getBase64(file: any) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

const CreateProductForm: React.FC<CreateProductFormProps> = ({
  modalVisible,
  onCancel}) => {
  //图片列表
  const [fileList, setFileList] = useState<any>([]);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');

  //处理预览
  const handlePreview = async (file: any) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewVisible(true);
  };
  //取消预览图片
  const handleCancel = () => setPreviewVisible(false);

  //删除图片的回调
  const handleRemove = (file: any) => {
    return new Promise<void>((resolve, reject) => {
      Modal.confirm({
        title: '确认删除这张图片吗？',
        onOk: () => {
          resolve(); //解析Promise，允许文件删除
        },
        onCancel: () => {
          reject(); //取消文件删除
        },
      });
    }).then(() => {
      // 只有当Promise被解析时，才执行删除逻辑
      const newFileList = fileList.filter((item: any) => item.uid !== file.uid);
      setFileList(newFileList);
    });
  };
  //限定图片大小
  const beforeUpload = (file: any) => {
    const isLt5M = file.size / 1024 / 1024 < 4;
    if (!isLt5M) {
      Modal.error({
        title: '错误',
        content: '图片必须小于4MB!',
      });
    }
    return isLt5M;
  };
  //图片改变
  const handleChange = ({ fileList }:any) => {
    setFileList(fileList);
  };

  //提交商品的回调
  const handleFinish = async (values: any) => {
    console.log('提交：', values);

    const { onOfflineTime,picture, ...otherValues } = values;
    const [onlineTime, offlineTime] = onOfflineTime;
    const finalValues={
      ...otherValues,
      onlineTime: onlineTime,
      offlineTime: offlineTime,
    }
    

    console.log('我把日期解构出来', finalValues);

    // try {
    //   const res = await shopsAddUsingPost(finalValues);
    //   if(res.code===200){
    //     message.success('提交成功');
    //     //刷新父组件
        
    //   }
    // } catch (error) {
    //   console.error('提交失败:', error);
    //   message.error('提交失败，请稍后再试');
    // }
  };

  const [form] = ProForm.useForm();

 


  //暂存为草稿的回调
  const saveDraft = () => {
    const formData = form.getFieldsValue();
    console.log('Draft data:', formData);
    // 处理暂存逻辑，formData 包含了整个表单的数据
  };
  return (
    <Modal
      width={1000}
      open={modalVisible}
      title="新增商品"
      onCancel={onCancel}
      footer={null}
    >
      <ProForm
       form={form}
        onFinish={handleFinish}
        submitter={{
          render: (_: any, dom: any[]) => [
            ...dom,
            //如何在自定义button里获取表单数据
            <Button key="custom" type="default" onClick={saveDraft}>
              <AlignLeftOutlined />
              暂存
            </Button>,
          ],
        }}
      >
        <Row gutter={24}>
          {' '}
          {/* gutter defines the spacing between columns */}
          <Col span={8}>
            <ProFormText
              name="name"
              label="商品名称"
              placeholder="请输入商品名称"
              rules={[{ required: true, message: '请输入商品名称' }]}
            />
          </Col>
        </Row>
        <Col span={12}>
          <ProFormTextArea
            name="description"
            label="商品描述"
            placeholder="请输入商品描述(不超过100字)"
            rules={[
              { required: true, message: '请输入商品描述' },
              { max: 100, message: '商品描述不能超过100个字' },
            ]}
          />
        </Col>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              name="picture"
              label="商品图片"
              rules={[{ required: true }]}
            >
              <div>
                <Upload
                  listType="picture-card"
                  fileList={fileList}
                  onPreview={handlePreview}
                  onChange={handleChange}
                  beforeUpload={beforeUpload}
                  onRemove={handleRemove}
                >
                  {fileList.length >= 1 ? null : (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>上传</div>
                    </div>
                  )}
                </Upload>
                <Modal
                  open={previewVisible}
                  footer={null}
                  onCancel={handleCancel}
                >
                  <img
                    alt="example"
                    style={{ width: '100%' }}
                    src={previewImage}
                  />
                </Modal>
              </div>
            </Form.Item>
          </Col>
        </Row>
        <Col span={6}>
          <ProFormSelect
            name="type"
            label="商品类型"
            placeholder="请选择商品类型"
            rules={[{ required: true, message: '请选择商品类型' }]}
            options={[
              { label: '普通商品', value: 'normal' },
              { label: '特殊商品', value: 'special' },
            ]}
          />
        </Col>

        <Row gutter={24}>
          <Col span={6}>
            <ProFormSelect
              name="supplierName"
              label="供应商名称"
              placeholder="请输入供应商名称"
              rules={[{ required: true, message: '请输入供应商名称' }]}
              options={[
                { label: '淘宝', value: 0 },
                { label: '拼多多', value: 1 },
              ]}
              />
            
          </Col>
          {/* <Col span={6}>
            <ProFormText
              name="supplierContact"
              label="供应商联系方式"
              placeholder="请输入供应商联系方式"
              initialValue={17835261534}
              rules={[
                { required: true, message: '请输入供应商联系方式' },
                {
                  pattern: /^1[3456789]\d{9}$/,
                  message: '请输入正确的手机号格式',
                },
              ]}
            />
          </Col> */}
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <ProFormTextArea
              name="serviceGuarantee"
              label="服务保障"
              placeholder="请输入服务保障内容(不超过100字)"
              rules={[
                { required: true, message: '请输入服务保障内容' },
                { max: 100, message: '服务保障内容不能超过100个字' },
              ]}
            />
          </Col>
        </Row>
        
         
           <ProFormList
           max={3}
           min={1}
          name="labels"
          copyIconProps={{ Icon: SmileOutlined, tooltipText: '复制' }}
          deleteIconProps={{
            Icon: CloseCircleOutlined,
            tooltipText: '删除',
          }}
        >
          <ProFormGroup key="group">
            <Row gutter={24}>
              <Col span={8}>
              <ProFormSelect
            name="type"
            label="价格类型"
            placeholder="请选择价格类型"
            rules={[{ required: true, message: '请选择价格类型' }]}
            options={[
              { label: '纯积分', value:0 },
              { label: '积分加钱', value: 1 },
              { label: '纯现金', value: 2 },
            ]}
          />
              </Col>
              <Col span={8}>
            <ProFormText name="pointPrice" label="积分数量" />
            </Col>
            <Col span={8} >
            <ProFormText name="cashPrice" label="现金价格" />
            </Col>
            </Row>
          </ProFormGroup>
        </ProFormList>
        

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              name="whiteCities"
              label="选择发货城市"
              rules={[{ required: true, message: '请选择发货城市' }]}
            >
              <Cascader
                style={{ width: '100%' }}
                options={options}
                // onChange={onChange}
                multiple
                maxTagCount="responsive"
              />
            </Form.Item>
          </Col>
        </Row>
        <Col span={12}>
          <Form.Item
            name="blackCities"
            label="选择不发货城市"
            rules={[{ required: true, message: '请选择不发货城市' }]}
          >
            <Cascader
              style={{ width: '100%' }}
              options={options}
              // onChange={onChange}
              multiple
              maxTagCount="responsive"
            />
          </Form.Item>
        </Col>

        <Row gutter={24}>
          <Col span={12}>
            <ProFormDateRangePicker
              width="md"
              name="onOfflineTime"
              label="上线时间-下线时间"
            />
          </Col>
        </Row>
        <Col span={6} style={{ marginBottom: 90 }}>
          <ProFormDigit
            name="exchangeLimit"
            label="兑换上限"
            placeholder="请输入兑换上限, -1表示没有限制"
            rules={[
              {
                required: true,
                type: 'number',
                min: -1,
                message: '兑换上限必须是数字',
              },
            ]}
          />
        </Col>
      </ProForm>
    </Modal>
  );
};

export default CreateProductForm;
